/**
 * 拉姆达表达式数据过滤
 */
export default class LambdaExpression {

    /**where条件查询 */
    public static where<T>(array: Array<T>, compareFn?: (t: T) => boolean):Array<T> {
        var newArray = [];
        array.forEach(element => {
            if (compareFn(element))  
                newArray.push(element); 
        }); 
        return newArray;
    }
   
     /**where条件查询 */
   public static whereDouble<T,R>(array: Array<T>,array2: Array<R>, compareFn?: (t: T,r:R) => boolean):Array<T> {
        var newArray = [];
        array.forEach(item => {
            array2.forEach(item2=>{
                if (compareFn(item,item2))  
                  newArray.push(item); 
            });
        }); 
        return newArray;
    }
      /**
       * 去重
       * @param array  去重数组
       * @param distinctFn  去重字段
       */
    public static distinct<T>(array: Array<T>, distinctFn?: (t: T) => any):Array<T> {
        var newArray = [];
        for (let i = 0; i < array.length; i++) {
            const item = array[i];
            var isok=false;
            for (let j =i+1; j < array.length; j++) {
                const item2 = array[j];
                if(distinctFn(item)==distinctFn(item2)){
                    isok=true;
                }
            }
            if(!isok){
                newArray.push(item);
            }
        }  
        return newArray;
    }
      /**
       * 获取新查询结果集
       * @param array  去重数组
       * @param selectFn  去重字段
       */
      public static select<T,R>(array: Array<T>, selectFn?: (t: T) => R):Array<R> {
        var newArray = [];
        for (let i = 0; i < array.length; i++) {
            newArray.push(selectFn(array[i])); 
        }  
        return newArray;
    }
     /**count 统计*/
     public static count<T>(array: Array<T>, compareFn?: (t: T) => boolean):number {
        var count = 0;
        array.forEach(element => {
            if (compareFn(element)) 
                count++; 
        }); 
        return count;
    }
    /**首条数据条件查询 */
    public static first<T>(array: Array<T>, compareFn?: (t: T) => boolean) { 
        for (let i = 0; i < array.length - 1; i++) {
            const element = array[i];
            if (compareFn(element)) {
                return element;
            }
        }
        return null;
    }
}